# -*- coding: utf-8 -*-

"""
Date: 2023/2/23 16:27
Author: Darker
"""
import pathlib
import os
import sys
import unicodedata
from typing import Text, Dict, Optional, NoReturn, List, Any

from utils import dump, load


class Config(object):

    def __init__(self):
        pathlib.Path(self.pictureDir).mkdir(parents=True, exist_ok=True)
        pathlib.Path(self.configDir).mkdir(parents=True, exist_ok=True)
        pathlib.Path(self.logDir).mkdir(parents=True, exist_ok=True)
        pathlib.Path(self.cacheFilePath).parent.mkdir(parents=True, exist_ok=True)

    @property
    def configPath(self) -> Text:
        return os.path.join(self.configDir, "tapdConf")

    @property
    def runLogPath(self) -> Text:
        return os.path.join(self.logDir, "run.log")

    @property
    def pictureDir(self) -> Text:
        return os.path.join(self.get_env_path(), "ZTCCLOUD_DailyReport", "picTemp")

    @property
    def configDir(self) -> Text:
        return os.path.join(self.get_env_path(), "ZTCCLOUD_DailyReport", "config")

    @property
    def logDir(self) -> Text:
        return os.path.join(self.get_env_path(), "ZTCCLOUD_DailyReport", "logs")

    @property
    def errorLogPath(self) -> Text:
        return os.path.join(self.get_env_path(), "ZTCCLOUD_DailyReport", "logs", "error.log")

    @property
    def cacheFilePath(self) -> Text:
        return os.path.join(self.get_env_path(), "ZTCCLOUD_DailyReport", "temp", "cache")

    @property
    def milestonePath(self) -> Text:
        return os.path.join(conf.pictureDir, "里程碑截图.png")

    @property
    def tapdList(self) -> List:
        return ['cookie', 'tapdUrl', 'id', 'startTime', 'smtpServer', 'userEmail', 'emailPassword', 'iterationId',
                'os1', 'releaseId', 'testPhase', 'dailyReportTittle', 'isIncludeHolidays', 'b1', 'address', 'mailCC',
                'dailyText',
                'milestoneAddress', 'milestoneExcel', 'manpowerToday', 'testSituation', 'tomorrowPlans', 'listOs',
                'listId', 'listIteration', 'listTestPhase', 'listReleaseId', 'win2Flag']

    @staticmethod
    def get_env_path() -> Optional[Text]:
        """
        获取当前用户家目录
        :return: None
        """
        match sys.platform:
            case "darwin" | "linux":
                return os.getenv("HOME")
            case "win32":
                return os.getenv("USERPROFILE")
            case _:
                raise

    def read_config(self) -> Dict:
        from log import logger
        """
        读取配置文件内容
        :return: 配置文件详情
        """
        filePath = pathlib.Path(self.configPath)
        if not filePath.exists():
            self.reset_config()
        configDict = load(conf.configPath)
        if not configDict or not configDict.get("TAPD"):
            self.reset_config()
            configDict = self.read_config()
        else:
            if len(set(configDict.get("TAPD").keys())) < len(set(self.tapdList)):
                logger.warn("配置文件不正确，已自动重置")
                self.reset_config()
                configDict = self.read_config()

        return configDict

    def reset_config(self) -> NoReturn:
        """
        重置/初始化配置
        :return: None
        """
        configDict = {
            "TAPD": {
                "cookie": "",
                "tapdUrl": "",
                "id": "",
                "startTime": "",
                "smtpServer": "smtp.exmail.qq.com",
                "userEmail": "xxx@ztccloud.com.cn",
                "emailPassword": "",
                "iterationId": "",
                "os1": "",
                "releaseId": "",
                "testPhase": "",
                "dailyReportTittle": "",
                "isIncludeHolidays": False,
                "b1": True,
                "address": "",
                "mailCC": "",
                "dailyText": "",
                "milestoneAddress": "",
                "milestoneExcel": "",
                "manpowerToday": "",
                "testSituation": "",
                "tomorrowPlans": "",
                "listOs": "测试环境_toolFlag_UAT环境_toolFlag_预发布环境_toolFlag_生产环境_toolFlag_项目环境",
                "listId": "产品_产品需求管理--67410840",
                "listIteration": "",
                "listTestPhase": "一轮测试_tooFlag_二轮测试_toolFlag_验收阶段_toolFlag_线上阶段_toolFlag_持续测试_toolFlag_通测阶段",
                "listReleaseId": "",
                "win2Flag": "N",
                "emailTitle": "测试组日报"
            },
            "SET": {"verse_token": ""}
        }
        dump(self.configPath, configDict)

    def modify_config(self, section, key, value) -> NoReturn:
        """
        修改配置文件，可用于新增配置文件
        :param section: 配置文件中的第一层key
        :param key: section中的新key
        :param value: key对应的值
        :return: None
        """
        confDict = self.read_config()
        if section not in confDict.keys():
            confDict[section] = {key: value}
        else:
            confDict[section][key] = value
        dump(self.configPath, confDict)

    def save_config(self, values: Dict):
        # 保存配置
        # move = dict.fromkeys((ord(c) for c in "\xa0\n\t"))
        # for k, v in values.items():
        #     for i, j in v.items():
        #         values[k][i] = unicodedata.normalize("NFKC", str(j).translate(move))

        dump(self.configPath, values)

    def delete_config(self) -> NoReturn:
        """
        删除配置文件
        :return: None
        """
        configPath = pathlib.Path(self.configPath)
        if configPath.exists():
            configPath.rmdir()

    def get_option(self, option: Text = None, section: Text = "TAPD") -> Any:
        """
        获取配置文件中的某个具体的配置值
        :param option: key
        :param section: 最外层key
        :return: Any
        """
        configDict = self.read_config()
        sectionData = configDict.get(section)
        if not option:
            return sectionData
        if isinstance(sectionData, Dict):
            return sectionData.get(option)

    def merge_config(self, newConfig: Dict) -> NoReturn:
        configData = self.read_config()
        for k, v in newConfig.items():
            configData["TAPD"][k] = v
        self.save_config(configData)


conf = Config()

if __name__ == '__main__':
    print(conf.reset_config())
